﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.UI.HtmlControls;

using SimpleText.Framework;
using System.Text;

public partial class TextsPage : SimpleTextPage 
{
	
  protected void Page_Load(object sender, EventArgs e)
  {
		InitPage();

		if (!IsPostBack)
		{
			SaveTexBtn.Attributes.Add("onclick", "if ( ! validateNewTextForm()) { return false;	}");
		}


		if (CurrentModel == null)
		{
			Response.Redirect("projects.aspx?msg=noprojectselected");
		}

		if (Request.QueryString["mode"] == "delete")
		{
			DeleteTextDefinition(Request.Form["textdefinitionname"]);
		}

		if (!IsPostBack)
		{
			TextDefListLit.Text = GetTextDefinitionsHtml();
		}
	}

	protected string GetTextDefinitionsHtml()
	{
		StringBuilder sb = new StringBuilder("");

		foreach (TextDefinition def in CurrentModel.TextDefinitions.Values)
		{
			string masterTextPreview = "";
			if (CurrentModel.MasterLanguageShortName != null)
			{
				if (def.Texts.ContainsKey(CurrentModel.MasterLanguageShortName))
				{
					Text masterText = def.Texts[CurrentModel.MasterLanguageShortName];
					if (masterText != null)
					{
						masterTextPreview = LimitLength(masterText.Content, 100);
					}
				}
			}
			sb.Append(
				String.Format(
				@"<tr>
						<td>
							{2}
						</td>
						<td>
							<a href=""text_edit.aspx?name={0}"">edit</a>
						</td>
						<td>

							<form action=""texts.aspx?mode=delete"" method=""post"" id=""delete_{0}"">
								<input type=""hidden"" name=""textdefinitionname"" value=""{0}"" />

								<a href=""javascript:void(deleteTextDefinition('{0}'));"">delete</a>
							</form>
						</td>					
					</tr>"
				, LimitLength(Server.HtmlEncode(def.Name), 50), Server.HtmlEncode(masterTextPreview), Server.HtmlEncode(def.Name)
				)
			);
		}

		return sb.ToString();
	}

	protected void DeleteTextDefinition(string definitionName)
	{
		CurrentModel.TextDefinitions.Remove(definitionName);

		SaveModel(CurrentModel, CurrentModel.LoadedFromXmlFilePath);
	}

	protected void CreateTextDefinitionBtnClicked(object sender, EventArgs e)
	{
		TextDefinition newTextDef = new TextDefinition();
		newTextDef.Name = NewNameTxt.Value;
		CurrentModel.TextDefinitions.Add(newTextDef.Name, newTextDef);

		SaveModel(CurrentModel, CurrentModel.LoadedFromXmlFilePath);

		Response.Redirect("text_edit.aspx?name=" + Server.UrlEncode(newTextDef.Name));
	}
}
